// components/delivery-address-card/delivery-address-card.js
import { setDefaultAddress, deleteDeliveryAddressById } from '../../service/delivery-address';

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    deliveryAddress: {
      type: Object,
      value: {},
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 是否为默认地址
    isDefault: 0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 向父页面发送点击的地址的id
     */
    sendDeliveryAddressIdToParentPage() {
      this.triggerEvent('sendDeliveryAddressIdToParentPage', this.data.deliveryAddress);
    },
    /**
     * 选择默认收获地址
     */
    async onTapChooseDefaultAddress() {
      await setDefaultAddress(this.properties.deliveryAddress.id);
      this.triggerEvent('update');
    },
    /**
     * 点击删除地址按钮
     */
    onTapDeleteButton() {
      const that = this;
      wx.showModal({
        content: '确定要删除该地址吗？',
        success: async function (res) {
          if (res.confirm) {
            await deleteDeliveryAddressById(that.properties.deliveryAddress.id);
            that.triggerEvent('update');
          } else if (res.cancel) {
          }
        },
      });
    },
    /**
     * 点击修改地址按钮
     */
    onTapModifyButton() {
      const option = encodeURIComponent(JSON.stringify(this.data));
      wx.navigateTo({
        url: `/pages/DeliveryAddress/ModifyDeliveryAddress/ModifyDeliveryAddress?option=${option}`,
      });
    },
  },
  /**
   * 生命周期
   */
  lifetimes: {
    attached() {
      this.setData({
        isDefault: this.properties.deliveryAddress.isDefault,
      });
    },
  },
});
